package com.xxx.third;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxx.common.enums.ThirdPartyType;
import com.xxx.common.model.RespEnum;
import com.xxx.exception.ServerException;
import com.xxx.common.constant.ThirdPartyConstants;
import com.xxx.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.codehaus.xfire.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方登录辅助类
 *
 * @author ShenHuaJie
 * @version 2016年5月20日 下午3:44:45
 */
@Slf4j
public final class ThirdPartyLoginHelper {

    /**
     * 获取QQ用户信息
     *
     * @param token
     * @param openid
     */
    public static final ThirdPartyUser getQQUserinfo(String token, String openid,String qqAppId)  {
        ThirdPartyUser user = new ThirdPartyUser();
        String url = ThirdPartyConstants.QQ_URL;
        url = url + "?format=json&access_token=" + token + "&oauth_consumer_key="
                + qqAppId + "&openid=" + openid;
        String res = HttpUtil.get(url);
        JSONObject json = JSON.parseObject(res);
        if (json.getIntValue("ret") == 0) {
            user.setUserName(json.getString("nickname"));
            String img = json.getString("figureurl_qq_2");
            if (img == null || "".equals(img)) {
                img = json.getString("figureurl_qq_1");
            }
            user.setAvatarUrl(img);
            String sex = json.getString("gender");
            if ("女".equals(sex)) {
                user.setGender(0);
            } else {
                user.setGender(1);
            }
        } else {
            throw new ServerException(RespEnum.USER_QQ_THIRD_INFO_ERROR);
        }
        user.setThirdPartyType(ThirdPartyType.QQ);
        user.setRemark(res);
        return user;
    }

    /**
     *  获取微信用户信息
     * @param token
     * @param openid
     * @return
     */
    public static final ThirdPartyUser getWxUserinfo(String token, String openid) {
        ThirdPartyUser user = new ThirdPartyUser();
        String url = ThirdPartyConstants.WINXIN_URL;
        url = url + "?access_token=" + token + "&openid=" + openid;
        String res = HttpUtil.get(url);
        JSONObject json = JSON.parseObject(res);
        if (json.getString("errcode") == null) {
            try {
                user.setUserName(new String(json.getString("nickname").getBytes("ISO-8859-1"),"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String img = json.getString("headimgurl");
            if (img != null && !"".equals(img)) {
                user.setAvatarUrl(img.replace("http://thirdwx.qlogo.cn","https://thirdwx.qlogo.cn"));
            }
            String sex = json.getString("sex");
            if ("0".equals(sex)) {
                user.setGender(0);
            } else {
                user.setGender(1);
            }
            user.setOpenid(json.getString("unionid"));
            user.setWechatOpenId(openid);
        } else {
            if(log.isErrorEnabled()){
                log.error(res);
            }
            throw new ServerException(RespEnum.USER_WE_CHART_THIRD_INFO_ERROR);
        }
        user.setRemark(res);
        user.setThirdPartyType(ThirdPartyType.WX);
        return user;
    }

    /**
     * 获取新浪用户信息
     *
     * @param token
     * @param uid
     * @return
     */
    public static final ThirdPartyUser getSinaUserinfo(String token, String uid)  {
        ThirdPartyUser user = new ThirdPartyUser();
        String url = ThirdPartyConstants.SINA_URL;
        url = url + "?access_token=" + token + "&uid=" + uid;
        String res = HttpUtil.get(url);
        JSONObject json = JSON.parseObject(res);
        String name = json.getString("name");
        String nickName = StringUtils.isBlank(json.getString("screen_name")) ? name : json.getString("screen_name");
        String avatarLarge = json.getString("avatar_large");
        user.setAvatarUrl(avatarLarge==null?null:avatarLarge.replace("http://","https://"));
        user.setUserName(nickName);
        if ("f".equals(json.getString("gender"))) {
            user.setGender(0);
        } else {
            user.setGender(1);
        }
        user.setToken(token);
        user.setOpenid(uid);
        user.setThirdPartyType(ThirdPartyType.SINA);
        user.setRemark(res);
        return user;
    }



    /**
     * 将格式为s1&s2&s3...的字符串转化成Map集合
     *
     * @param str
     * @return
     */
    private static final Map<String, String> toMap(String str) {
        Map<String, String> map = new HashMap<String, String>();
        String[] strs = str.split("&");
        for (String str2 : strs) {
            String[] ss = str2.split("=");
            map.put(ss[0], ss[1]);
        }
        return map;
    }

    /**
     * 小程序获取的信息解密
     */
    public static String geDecodeInfo(String encryptedData, String sessionkey, String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return result;
            }else{
                if(log.isErrorEnabled()) {
                    log.error("参数:encryptedData->{}sessionkey->{}iv->{}",new Object[]{encryptedData,sessionkey,iv});
                }
            }
        } catch (Exception e) {
            if(log.isErrorEnabled()) {
                log.error("参数:encryptedData->{}sessionkey->{}iv->{}",new Object[]{encryptedData,sessionkey,iv});
                log.error(e.getMessage(), e);
            }
            throw new ServerException(RespEnum.USER_WE_CHART_MINI_INFO_ERROR);
        }
        return null;
    }
}
